package com.tul.exercise.base.java8.stream.sort;

import com.tul.exercise.base.java8.stream.base.Apple;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 元素排序
 *
 * @author tuliang
 */
public class SortTest {
    @Test
    @DisplayName("元素排序")
    public void test01() {

        List<String> list = Arrays.asList("tuliang", "lisi", "zhoutao");
        Stream<String> stringStream = Stream.of("tuliang", "lisi", "zhoutao");
        Assertions.assertEquals(list, stringStream.collect(Collectors.toList()));

        Set<String> set = new HashSet<>(list);
        List<String> setList = set.stream().collect(Collectors.toList());
        // 该断言会失败
        Assertions.assertEquals(set, setList);
    }

    @Test
    @DisplayName("按照对象某个字段排序")
    public void test02() {
        List<Apple> apples = Apple.createApples(3);


        // 按照对象某个字段排序，使用函数引用
        List<Apple> sortedList = apples.stream().sorted(Comparator.comparing(Apple::getWeight))
                .collect(Collectors.toList());
        sortedList.stream().forEach(System.out::println);

        // 按照对象某个字段排序，使用lambda表达式
        List<Apple> sortedList2 = apples.stream().sorted((a, b) -> a.getWeight().compareTo(b.getWeight()))
                .collect(Collectors.toList());
        sortedList2.stream().forEach(System.out::println);

        // 排序后反序
        List<Apple> sortedList3 = apples.stream().sorted(Comparator.comparing(Apple::getWeight)
                .reversed()).collect(Collectors.toList());
        sortedList3.stream().forEach(System.out::println);

        // 对原序列排序，不使用Stream
        List<Apple> apples2 = Apple.createApples(3);
        apples2.sort(Comparator.comparingDouble(Apple::getWeight));
        apples2.stream().forEach(System.out::println);
    }

    @Test
    @DisplayName("按照对象多个字段排序")
    public void test03() {
        List<Apple> apples = Apple.createApples(10);

        // 对原序列进行排序
        apples.sort(Comparator.comparingDouble(Apple::getWeight)
                .thenComparing(Apple::getColor)
                .thenComparing(Apple::getName));
        apples.stream().forEach(System.out::println);


        // 使用stream排序，之后转换成另一个List
        List<Apple> list = apples.stream().sorted(Comparator.comparingDouble(Apple::getWeight)
                .thenComparing(Apple::getColor)
                .thenComparing(Apple::getName))
                .collect(Collectors.toList());
        list.forEach(System.out::println);

    }
}
